﻿/// <reference path="../../Scripts/jquery-1.7.2-vsdoc.js" />
/// <reference path="../ThirdParty/livequery/jquery.livequery.js" />


// create core namespace
var Proggy = {};

// global functions
Proggy.Global = function () {

    // set nav
    var setNav = function () {

        // get nav
        var navItems = jQuery("#navUl > li");

        // set
        navItems.each(function () {
            // get item
            var item = jQuery(this);

            // get nested
            var nested = item.find("ul:eq(0)");

            // hide
            nested.hide();

            // bind hover
            item.hover(function () {
                nested.slideDown(200);
            },
            function () {
                nested.slideUp(200);
            });
        });


    };

    // success
    var checkForSuccess = function () {
        Proggy.Static.CheckForSuccess();
    };

    // binds certain links /forms into lightbox 
    var bindLightboxLinksAndForms = function () {

        // get links
        var links = jQuery("a.proggy-lb-link-init");

        // bind
        links.on("click", null, null, function (e) {

            // get link
            var link = jQuery(this);

            // bind
            Proggy.Static.InitialLoadIntoLightbox(link, e);

        });

        // forms
        jQuery("body").on("submit", ".proggy-lb-form-within", function () {

            // get form
            var form = jQuery(this);

            // submit
            Proggy.Static.OnSubmittingFormWithinLightbox(form);

            // 
            return false;

        });

    };

    // bind unload
    var bindUnload = function () {

        // bind
        window.onunload = function () {

            //
            Proggy.Static.IterateBeforeUnloadMethods(function () {

            });

        };
    };

    // set on error
    var setOnError = function () {

        // set
        window.onerror = function (message, url, linenumber) {

            alert(
                "DO SOMETHING BETTER HERE BUT... \n\nError:\n\n" + message +
                "\nat line " + linenumber + " in " + url);

        };

        // set
        jQuery.ajaxSetup({

            // 
            beforeSend: function (xhr, settings) {

                // set last url
                window.LAST_AJAX_URL = settings.url;
            },

            //
            error: function (xhr, textStatus, errorThrown) {

                // create text
                var text =
                    "DO SOMETHING BETTER HERE BUT..." +
                    "\n\n" + errorThrown +
                    "\n\n(Requesting " + window.LAST_AJAX_URL + ")" +
                    "\n\nClose all dialogs and save your work";

                alert(text);
            }
        });
    };

    // show all
    var showAll = function () {
        jQuery("div#all").show();
    };


    //
    this.Init = function () {

        // dom ready
        jQuery(function () {

            // set error handling
            setOnError();

            // set types registered
            window.TYPES_REGISTERED = true;

            // run functions
            setNav();

            // check for "success"
            checkForSuccess();

            // bind lightbox
            bindLightboxLinksAndForms();

            //  bind unload
            bindUnload();

            // show
            showAll();

        });
    };
};

// static functions
Proggy.Static = {

    // preview window
    PreviewWindow: undefined,

    // bind preview button
    BindPreview: function () {

        // 
        Proggy.Static.AddToBeforeUnloadMethods(function () {

            //
            if (Proggy.Static.PreviewWindow != undefined) {

                //
                Proggy.Static.PreviewWindow.close();
            };

        });

        // get buttons
        var buttons = jQuery("a.proggy-content-preview");

        // bind
        buttons.click(function (e) {

            //
            e.preventDefault();

            // get button
            var button = jQuery(this);

            // get href
            var href = button.attr("href");

            // check
            if (Proggy.Static.PreviewWindow == undefined) {

                // go
                Proggy.Static.PreviewWindow = window.open(href, "_blank");

                // set unload
                Proggy.Static.PreviewWindow.onunload = function () {
                    Proggy.Static.PreviewWindow = null;
                };
            }
            else {

                // refresh
                Proggy.Static.PreviewWindow.location = href;
            }

            // focus window
            Proggy.Static.PreviewWindow.focus();
        });
    },

    // check for success
    CheckForSuccess: function () {
        // find
        var success = jQuery("#success");

        // hide
        success.hide();

        // show then hide again
        success.fadeIn("slow", function () {

            // pause
            window.setTimeout(function () {

                // hide
                success.fadeOut("slow", function () {

                    // remove
                    success.remove();

                });

            }, 5000);
        });
    },

    // load content
    InitialLoadIntoLightbox: function (linkEl, e, callbackWithElements) {

        //window.TYPES_REGISTERED = false;

        if (typeof (e) == "function") {
            callbackWithElements = e;
        }
        else {

            // prevent nav
            e.preventDefault();

        }

        // show loader
        this.ShowLoader(function (lb, lbInner) {

            // start response
            var response;

            // get
            jQuery.ajax(linkEl.attr("href"), {

                async: false,
                success: function (r, s, x) {

                    // set response
                    response = jQuery(r);
                }

            });

            // hide loadING
            Proggy.Static.HideLoader(false, lb, lbInner,

            // before show            
            function () {

                // add reponse
                lbInner.append(response);

                // get title
                var ttle = lbInner.find(".proggy-lb-title");
                var ttleText = ttle.html();


                // remove
                ttle.remove();

                // add to dialog
                lb.dialog("option", "title", ttleText);

            },

            // after show
            function () {

                // check
                if (callbackWithElements != undefined && typeof (callbackWithElements) == "function") {
                    callbackWithElements(lb, lbInner);
                };


            });

        });

    },

    // when form submitted, response is always posted into lightbox
    OnSubmittingFormWithinLightbox: function (form, callbackWithElements) {

        // get els
        var lb = jQuery(form).parentsUntil(".ui-dialog", ".proggy-lb");
        var lbInner = lb.children(".proggy-lb-inner:eq(0)");

        //
        // get data
        var data = form.serialize();
        var action = form.attr("action");
        var method = form.attr("method");

        // show loader
        Proggy.Static.ShowTempLoader(lb, lbInner, function () {

            // start response
            var response;

            // post
            jQuery.ajax(action, {

                async: false,
                type: method,
                data: data,
                success: function (r, s, x) {

                    // set response
                    response = jQuery(r);

                }
            });

            // hide
            Proggy.Static.HideLoader(false, lb, lbInner,

            // before
                function () {

                    // console.log("At this point, methods should have run");

                    // add reponse
                    lbInner.append(response);

                    // get title
                    var ttle = lbInner.find(".proggy-lb-title");
                    var ttleText = ttle.html();

                    // remove
                    ttle.remove();

                    // add to dialog
                    lb.dialog("option", "title", ttleText);

                },

            // after
                function () {

                    // check
                    if (callbackWithElements != undefined && typeof (callbackWithElements) == "function") {
                        callbackWithElements(lb, lbInner);
                    };

                });

        });
    },

    // show loader
    ShowLoader: function (callbackWithElements) {

        //
        window.TYPES_REGISTERED = false;

        // add lightbox
        jQuery("body").append("<div class=\"proggy-lb\"><div class=\"proggy-lb-inner proggy-lb-inner-loading\"></div></div>");

        // get lightbox
        var lb = jQuery("body > .proggy-lb").last();

        // get inner
        var lbInner = lb.find(".proggy-lb-inner");

        // modalise
        lb.dialog({
            autoOpen: false,
            draggable: false,
            height: 600,
            width: 1012,
            resizable: false,
            modal: true,
            show: "fade",
            title: "Loading...",
            open: function (e, ui) {
                callbackWithElements(lb, lbInner);
            },
            dialogClass: "proggy-lb-class",
            close: function (e, ui) {
                lb.dialog("destroy");
                lb.remove();
            }
        });

        // open
        lb.dialog("open");

    },

    // lightbox already exists
    ShowTempLoader: function (lb, lbInner, callback) {

        lb.dialog("option", "title", "Loading...");
        lbInner.html("").addClass("proggy-lb-inner-loading");
        callback();

    },

    // hideload
    HideLoader: function (removeDialog, lb, lbInner, beforeShow, callbackWithElements) {

        // check
        if (removeDialog && beforeShow != undefined) {
            callbackWithElements = beforeShow;
        };

        // check
        if (removeDialog) {

            Proggy.Static.IterateMethods(true);

            //
            if (callbackWithElements != undefined) {
                callbackWithElements(lb, lbInner);
            }

            lb.dialog("close");

            return;

        }
        else {

            // fade
            lbInner.fadeTo(200, 0, function () {

                // remove load
                lbInner.removeClass("proggy-lb-inner-loading");
                lb.dialog("option", "title", "");
                beforeShow();

                // check
                //console.log(Proggy.Static.BeforeLightboxContentShowMethods);
                Proggy.Static.IterateMethods(false);

                // fade up
                lbInner.fadeTo(200, 1, function () {

                    // callback
                    callbackWithElements(lb, lbInner);

                });

            });
        };

    },

    // methods to run after lightbox loads (before show)
    BeforeLightboxContentShowMethods: [],

    // add to the above
    AddToBeforeLightboxContentShowMethods: function (method) {

        // add
        this.BeforeLightboxContentShowMethods.push(method);
    },

    // iterates the above
    IterateMethods: function (isRemoveDialog) {

        // private
        function scrollToTop() {
            jQuery(".ui-dialog-content").scrollTop(0);
        };

        //
        if (!isRemoveDialog) {

            /***** first... UNREGISTER TYPES *****/
            window.TYPES_REGISTERED = false;

            /**** then... check for content added on the fly in head ****/
            Proggy.Static.CheckForAddedContent();

            // scroll
            scrollToTop();

            /***** finally, iterate methods *****/
            jQuery.each(Proggy.Static.BeforeLightboxContentShowMethods, function (index, method) {
                method();
            });
        }

    },

    // checks for content added via javascript
    CheckForAddedContent: function () {

        // private
        function checkAddedContent() {

            // get head
            var head = jQuery("head");
            //var body = jQuery("body");
            //console.log(head.find("script"));

            // get els
            //var stylesAdded = head.find("link.proggy-added-head-content");
            //var jsAdded = head.find("script.proggy-added-head-content");


            // remove
            //stylesAdded.remove();
            //jsAdded.remove();


            /***** then check for lightbox content *****/
            if (window.LIGHTBOX_CONTENT != undefined) {

                // iterate
                for (var counter = 1; window.LIGHTBOX_CONTENT.length >= counter; counter++) {


                    // start bool to add
                    var add = true;

                    // get item
                    var theItem = window.LIGHTBOX_CONTENT[(counter - 1)];

                    // check type
                    if (theItem.type == "Stylesheet") {

                        // get match
                        var match = head.find('link[href="' + theItem.path + '"]');
                        add = match.size() == 0;

                    };

                    // check add
                    if (add) {

                        // check type
                        if (theItem.type == "Stylesheet") {
                            var linkHtml = "<link class=\"proggy-added-head-content\" rel=\"stylesheet\" href=\"" + theItem.path + "\" />";
                            head.append(linkHtml);
                        };

                        // check type
                        if (theItem.type == "JavaScript") {

                            // get bools
                            var noReg = window.LIGHTBOX_CONTENT_REGISTRATION == undefined;
                            var alreadyIn = jQuery.inArray(theItem.path, window.LIGHTBOX_CONTENT_REGISTRATION) != -1;

                            // check
                            if (!alreadyIn) {

                                // try cached
                                jQuery.ajax(theItem.path, {

                                    async: false,
                                    cache: false,
                                    dataType: "script",
                                    success: function (d, t, x) {

                                        // check registration
                                        if (noReg) {

                                            window.LIGHTBOX_CONTENT_REGISTRATION = [];
                                            noReg = false;

                                        };

                                        //
                                        //console.log(window.LIGHTBOX_CONTENT_REGISTRATION);

                                        // add
                                        window.LIGHTBOX_CONTENT_REGISTRATION.push(theItem.path);
                                    }

                                });
                            };

                        };

                    }
                };

                // ok
                window.TYPES_REGISTERED = true;
            }
        };

        //
        checkAddedContent();
    },

    // waits for any content added on the fly to be loaded
    WaitForTypesToRegister: function (callback) {

        //private
        //function start() {

        var theTimeout = window.setTimeout(function () {

            // check
            if (window.TYPES_REGISTERED != undefined && window.TYPES_REGISTERED == true) {

                // 
                window.clearTimeout(theTimeout);

                // ok
                callback();


            }
            else {

                // 
                window.clearTimeout(theTimeout);
                Proggy.Static.WaitForTypesToRegister(callback);

                //                // try again
                //                window.setTimeout(function () {


                //                    start();


                //                }, 10);
            }

        }, 100);

        //};

        // start loop
        //start();

    },

    // before unload methods
    BeforeUnloadMethods: [],

    // add to methods
    AddToBeforeUnloadMethods: function (method) {

        this.BeforeUnloadMethods.push(method);

    },

    // iterate methods
    IterateBeforeUnloadMethods: function (callback) {

        // start counter
        var counter = 0;

        // private
        function iterateMethod(finalCallback) {

            // check
            if (Proggy.Static.BeforeUnloadMethods[counter] != undefined) {

                // get
                var theFunc = Proggy.Static.BeforeUnloadMethods[counter];

                // run
                theFunc(function () {

                    // add
                    counter++;
                    iterateMethod(finalCallback);

                });

            }
            else {
                finalCallback();
            }

        };

//        // set unloading
//        jQuery.ajax(window.ROOT_URL + "Proggy/Utility/StartUnloading", {
//            async: false,
//            type: "POST",
//            success: function (r, s, x) {

//                //
//                //console.log(r);

//                // iterate
//                iterateMethod(function () {

//                    // stop unloading
//                    jQuery.ajax(window.ROOT_URL + "Proggy/Utility/StopUnloading", {

//                        async: false,
//                        type: "POST",
//                        success: function (r_, s_, x_) {
//                            //console.log(r_);
//                        }

//                    });

//                })

//            }
//        });

    },

    // get lightbox
    GetLightbox: function (stackIndex) {
        return jQuery(".proggy-lb:eq(" + stackIndex + ")");
    },
    GetLightboxInner: function (lb) {
        return lb.find(".proggy-lb-inner:first");
    }

};